﻿using AutoMapper;
using B.S.Traceability.Domain;
using B.S.Traceability.Error;
using B.S.Traceability.Infrastructure.Interface;
using B.S.Traceability.Writer.API.Application.Commends.Farmss;
using MediatR;

namespace B.S.Traceability.Writer.API.Application.CommendHandlers.Farmss
{
    public class CreateFarmCommendHandlers : IRequestHandler<CreateFarmCommends, APIResult<Farms>>
    {

        private readonly IBaseRepository<Farms> farmsRepository;
        private readonly IMapper mapper;

        public CreateFarmCommendHandlers(IBaseRepository<Farms> farmsRepository, IMapper mapper)
        {
            this.farmsRepository = farmsRepository;
            this.mapper = mapper;
        }

        /// <summary>
        /// 添加养殖信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<APIResult<Farms>> Handle(CreateFarmCommends request, CancellationToken cancellationToken)
        {
            APIResult<Farms> result = new APIResult<Farms>();
            result.Code = APIEnum.添加成功;
            result.Msg= "添加成功";
            var  exist =  farmsRepository.GetAllAsync().Result.FirstOrDefault(x => x.BatchId == request.BatchId);
            if (exist == null) {
                var farm = mapper.Map<Farms>(request);

                farm.BatchId = request.BatchId;
                result.Code = APIEnum.添加成功;
                result.Msg = "添加成功";
                await farmsRepository.Add(farm);
            }
            else
            {
                mapper.Map(request,exist);
                await farmsRepository.Update(exist);
                result.Code = APIEnum.修改成功;
                result.Msg = "修改成功   ";
            }
 
            return await  Task.FromResult(result);

       
        }
    }
}
